<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <a-icon slot="indicator" type="loading" style="font-size: 24px" spin />
    <div class="analysis">
      <div class="table mt20">
        <div class="top-filter flex-between mb10">
          <div
            class="strong fs16 mrSemiBold flex-center"
            style="color: #110000"
          >
            <div class="outer">
              <div class="inner"></div>
            </div>
            文章管理
          </div>
        </div>

        <div class="consultation-block">
          <div style="display: flex;gap: 20px;">
            <el-input style="width: 200px;" size="mini" v-model="keywords" placeholder="请输入文章标题"></el-input>
            <el-select clearable v-if="userInfo.admin" style="width: 200px;" size="mini" v-model="creatorId" placeholder="请选择文章发布人">
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.username"
                :value="item.id">
              </el-option>
            </el-select>
            <el-button type="primary" size="mini" @click="refreshTable('init')"
            >查询</el-button>
            <el-button type="primary" size="mini" @click="openDialog('add')"
            >添加文章</el-button>
          </div>
          <div class="table" v-loading="tableLoading">
            <el-table size="mini" :data="tableData" style="width: 100%">
              <el-table-column label="序号" type="index"> </el-table-column>
              <el-table-column prop="creator" label="作者"> </el-table-column>
              <el-table-column prop="createTime" label="创建时间">
              </el-table-column>
              <el-table-column prop="title" label="标题"> </el-table-column>
              <el-table-column prop="type" label="分类"> </el-table-column>
              <el-table-column prop="lang" label="语言"> </el-table-column>
              <el-table-column prop="status" label="审核状态" :formatter="formatStatus"> </el-table-column>
              <el-table-column label="操作" width="250">
                <template slot-scope="scope">
                  <el-button
                    type="warning"
                    size="mini"
                    v-if="userInfo.admin || userInfo.id == scope.row.creatorId"
                    @click="openDialog('edit', scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="success"
                    size="mini"
                    v-if="userInfo.admin && !scope.row.status"
                    @click="doSH(scope.row)"
                    >审核</el-button
                  >
                  <el-button
                    type="danger"
                    v-if="userInfo.admin || userInfo.id == scope.row.creatorId"
                    size="mini"
                    @click="deleteData(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next"
              :current-page.sync="currentPage"
              @current-change="handleCurrentChange"
              :page-size="pageSize"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
        <el-dialog
          :title="dialogTitle"
          :visible.sync="isVisible"
          width="60%"
          :before-close="handleClose"
        >
          <el-form
            :model="form"
            status-icon
            :rules="rules"
            ref="form"
            size="mini"
            label-width="120px"
            class="demo-form"
          >
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="type">
              <el-select style="width: 100%;" v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="语言" prop="lang">
              <el-select style="width: 100%;" v-model="form.lang" placeholder="请选择">
                <el-option
                  v-for="item in langs"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <editor-bar v-model="form.content" :isClear="isClear"></editor-bar>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer" v-if="!form.examine">
            <el-button type="primary" @click="submitForm()">提 交</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </a-spin>
</template>

<script>
import {
  getExpense,
  getUser,
  updateExpense,
  addExpense,
  updateUser
} from "../../../service";
import EditorBar from '../../../components/wangEnduit'
import moment from "moment";
export default {
  name: "Analysis",
  components: { EditorBar },
  i18n: require("./i18n"),
  data() {
    return {
      tableData: [],
      keywords: '',
      currentPage: 1,
      pageSize: 10,
      priceInfo: {},
      total: 0,
      tableLoading: false,
      isVisible: false,
      dialogTitle: "",
      form: {
        title: "",
        content: ""
      },
      userList: [],
      rules: {
        title: [{ required: true, message: '不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '不能为空', trigger: 'blur' }],
        lang: [{ required: true, message: '不能为空', trigger: 'blur' }],
      },
      u: {},
      userInfo: {},
      creatorId: '',
      spinning: false,
      options: ['诗歌', '散文', '小说'],
      langs: ['中文', '英文'],
      isClear: false,  
      detail:""
    };
  },
  watch: {
    $route(to) {
      if (to.path === "/page/waste") {
        this.refreshTable();
        getUser({
          pageSize: 1000
        }).then(res => {
          this.userList = res.data.data
        })
      }
    },
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem('articleWebInfo'))
    this.refreshTable();
    getUser({
      pageSize: 1000
    }).then(res => {
      this.userList = res.data.data
    })
  },
  methods: {
    openDialog(type, row = {}) {
      if (type === 'add') {
        this.dialogTitle = "添加";
        this.form = {
          title: '',
          content: '',
          type: '',
          lang: ''
        };
      } else {
        this.dialogTitle = "编辑";
        this.form = row;
      }
      this.isVisible = true;
    },
    handleClose() {
      this.isVisible = false;
    },
    handleCurrentChange(index) {
      this.currentPage = index
      this.refreshTable()
    },
    formatStatus(row) {
      return row.status ? '已审核' : '未审核'
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === "添加") {
            addExpense({
              ...this.form,
              createTime: moment().format('YYYY-MM-DD HH:mm:ss'),
              creator: JSON.parse(localStorage.getItem('articleWebInfo')).username,
              creatorId: JSON.parse(localStorage.getItem('articleWebInfo')).id,
              status: this.userInfo.admin ? 'true' : '',
              isDelete: '',
              deleteTime: ''
            }).then(res => {
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.refreshTable();
                this.isVisible = false;

                // 积分
                let count = this.form.content.length
                // 
                updateUser(this.userInfo.id, {
                  score: Number(this.userInfo.score) + Math.floor(count / 100)
                }).then(res => {
                  console.log(res)
                })
              } else {
                this.$message.error(res.msg || '操作失败');
              }
            })
            return
          }
          updateExpense(this.form.id, {
            ...this.form
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success("操作成功");
              this.refreshTable();
              this.isVisible = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    addData() {
      this.dialogTitle = "新增";
      this.isVisible = true;
    },
    refreshTable(init = '') {
      if (init) {
        this.currentPage = 1;
      }
      getExpense({
        page: this.currentPage,
        pageSize: this.pageSize,
        isDelete: '',
        title: this.keywords,
        creatorId: this.userInfo.admin ? this.creatorId : this.userInfo.id,
      }).then((res) => {
        this.tableData = res.code === 200 && res.data.data ? res.data.data : [];
        this.total = res.data.total || 0
      });
    },
    updateData(row) {
      this.form = {
        ...row
      };
      this.dialogTitle = "修改";
      this.isVisible = true;
    },
    deleteData(row) {
      this.$confirm("删除文章至回收站, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateExpense(row.id, {
            isDelete: 'true',
            deleteTime: moment().format('YYYY-MM-DD HH:mm:ss')
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success("操作成功");
              this.refreshTable();
              this.isVisible = false;
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    doSH(row) {
      updateExpense(row.id, {
        status: 'true'
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.refreshTable();
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.analysis {
  margin-top: 20px;
  border-radius: 10px;
  width: 100%;

  .right {
    padding: 20px;
  }

  .content {
    background: #ebebeb;
    height: 500px;
    padding: 12px;
    border-radius: 10px;
  }

  .top {
    & > div {
      width: 50%;
      padding: 20px 16px;
    }
    background: #fff;
    display: flex;
    border-radius: 10px;
  }
}

.diy-btn {
  width: 60%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin: auto;
  border-radius: 20px;
  cursor: pointer;
}
.diy-btn-hover:hover {
  color: #fff;
  background-color: #9254de;
  border-color: #9254de;
}
.danger-btn-hover:hover {
  color: #fff;
  background-color: #ff7875;
  border-color: #ff7875;
}
.black-btn-hover:hover {
  color: #fff;
  background-color: #655c5c !important;
  border-color: #655c5c;
}
.mt50 {
  margin-top: 50px;
}

.btns {
  width: 60%;
  margin-left: 20%;
  display: flex;
  justify-content: space-around;
  & > div {
    height: 40px;
    line-height: 40px;
    color: #fff;
    text-align: center;
    border-radius: 20px;
    cursor: pointer;
  }
}
.card-each {
  flex: 1;
  height: 80px;
  background: #fff;
  border-radius: 2px;
  padding: 20px;
}
.table {
  background: #fff;
  padding: 20px;
}
</style>
